package com.ztky.report.command;

import java.io.File;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JasperCompileManager;

/**
 * 启动时编译模板文件至jrxml->jasper
 */
@Component
public class InitJasperreport implements CommandLineRunner {
	
	private static final Logger log = LoggerFactory.getLogger(InitJasperreport.class);
	
	/**
	 * 报表文件根目录，以/结尾
	 */
	@Value("${report.root.dir}")
	private String reportRootDir;

	@Override
	public void run(String... strings) throws Exception {
		if (!reportRootDir.endsWith("/")) {
			reportRootDir = reportRootDir + "/";
		}
		File root = new File(reportRootDir);
		loadFile(root);
		// JasperCompileManager.compileReportToFile(InitJasperreport.class.getClassLoader().getResource("").getPath()+"jasper/TableReport.jrxml");
	}

	private void loadFile(File root) throws JRException {
		if (root == null || !root.exists()) {
			return;
		}

		if (root.isDirectory()) {
			File[] lists = root.listFiles();
			for (File file : lists) {
				loadFile(file);
			}
		} else {
			String name = root.getName();
			if (name.toLowerCase().endsWith(".jrxml")) {
				log.info("编译报表文件:{}", root.getAbsolutePath());
				JasperCompileManager.compileReportToFile(root.getAbsolutePath());
			}
		}

	}
}
